package com.example.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.ruiji.common.Result;
import com.example.ruiji.entity.AddressBook;
import com.example.ruiji.mapper.AddressBookMapper;
import com.example.ruiji.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    HttpSession httpSession;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public Result<AddressBook> save(AddressBook addressBook) {
        addressBook.setUserId((Long) httpSession.getAttribute("userId"));
        addressBookMapper.insert(addressBook);
        return Result.success(addressBook);
    }

    @Override
    public Result<AddressBook> setDefault(AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.eq(AddressBook::getUserId, (Long) httpSession.getAttribute("userId"));
        lambdaQueryWrapper.set(AddressBook::getIsDefault, 0);
        addressBookMapper.update(null, lambdaQueryWrapper);
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
        return Result.success(addressBook);
    }

    @Override
    public Result<AddressBook> getById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        if (!Objects.isNull(addressBook)) {
            return Result.success(addressBook);
        }
        return Result.error("地址不存在");
    }

    @Override
    public Result<AddressBook> getDefault() {
        LambdaUpdateWrapper<AddressBook> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.eq(AddressBook::getUserId, (Long) httpSession.getAttribute("userId"));
        lambdaQueryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookMapper.selectOne(lambdaQueryWrapper);

        if (!Objects.isNull(addressBook)) {
            return Result.success(addressBook);
        }
        return Result.error("地址不存在");
    }

    @Override
    public Result<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId((Long) httpSession.getAttribute("userId"));
        LambdaUpdateWrapper<AddressBook> lambdaQueryWrapper = new LambdaUpdateWrapper<>();
        lambdaQueryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, (Long) httpSession.getAttribute("userId"));
        lambdaQueryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookMapper.selectList(lambdaQueryWrapper);
        return Result.success(addressBooks);
    }
}
